let express = require('express')

let router = express.Router()
let bcrypt = require('../../utils/bcrypt')
let jwt = require('../../utils/jwt')


router.get('/',(req,res,next)=>{

  let {username,password} = req.query;

  //设定了必传参数
  if(!username || !password){
    res.send({
      err:1,msg:'用户名或者密码为必传参数'
    })
    return;
  }

  //开库
  req.mgdb.open({
    collectionName:'user'
  }).then(
    ({collection,client})=>{
      //兜库
      collection.find({username}).toArray((err,result)=>{
        if(err){
          res.send({err:1,msg:'操作集合失败'+ err })
          client.close()
        }else{
          if(result.length>0){
            //校验密码
            let bl = bcrypt.compareSync(password,result[0].password)
            if(bl){
              //密码通过 生成token
              let token = jwt.sign({username,_id:result[0]._id})
              delete result[0].username;
              delete result[0].password;
              res.send({err:0,msg:'登陆成功',data:result[0],token})
              client.close()
            } else {
              res.send({err:1,msg:'用户名和密码有误'});
              client.close()
            }
          }else{
            res.send({err:1,msg:'用户名和密码有误'});
            client.close()
          }
        }
      })
    }
  ).catch(
    mess => res.send(mess)
  )

})

module.exports=router;